<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
	getGroupDimensions,
	getOutputFields,
	validateConditions,
	summaryQuery,
	dataQuery,
	rawDataQuery,
	exportQuery
} from '@/assets/api/MultipleQueries.js'

// 英文字段 -> 中文显示名
const labelMap = {
	customs_area: '关区',
	declare_no: '报关单号',
	item_no: '商品项号',
	import_export_type: '进出口类型',
	record_count: '记录数量',
	declaration_count: '报关单数量',
	// 输出字段（下划线）
	amount_cny: '货值(人民币)',
	amount_usd: '货值(美元)',
	goods_quantity: '商品数量',
	declare_count: '报关单数量',
	// 汇总结果（驼峰）
	dimensionValues: '维度值',
	declareCount: '报关单数量',
	recordCount: '记录数量',
	amountCny: '货值(人民币)',
	amountUsd: '货值(美元)',
	goodsQuantity: '商品数量',
	level: '层级',
	drillable: '可下钻',
	drillPath: '下钻路径'
}
const toLabel = (key) => labelMap[key] || key

// 数据类型转换函数
const getDataTypeLabel = (dataType) => {
	const typeMap = {
		1: 'FTP导入',
		2: 'CSV上报', 
		3: '手工录入',
		4: '主动采集'
	}
	return typeMap[dataType] || dataType
}

// 货币类型转换函数
const getCurrencyTypeLabel = (currencyType) => {
	const currencyMap = {
		1: '人民币',
		2: '美元'
	}
	return currencyMap[currencyType] || currencyType
}

// 状态转换函数
const getStatusLabel = (status) => {
	const statusMap = {
		1: '待入库',
		2: '已入库',
		3: '异常'
	}
	return statusMap[status] || status
}

// 基本状态
const activeTab = ref('summary')
const loading = ref(false)

// 查询条件（与后端 DTO 对齐）
const form = reactive({
	queryType: 'SUMMARY_QUERY',
	importExportType: '',
	customsCode: '',
	customsClearanceStartDate: '',
	customsClearanceEndDate: '',
	groupDimensions: [],
	outputFields: [],
	filterConditions: {},
	pageNum: 1,
	pageSize: 20
})

// 可选项
const groupDimensionOptions = ref([])
const outputFieldOptions = ref([])

// 关区列表（由后端汇总 customs_area 生成）
const customsOptions = ref([])

// 数据
const tableData = ref([])
const total = ref(0)

const dateRange = ref([])

const updateTypeByTab = () => {
	if (activeTab.value === 'summary') form.queryType = 'SUMMARY_QUERY'
	else if (activeTab.value === 'data') form.queryType = 'DATA_QUERY'
	else form.queryType = 'RAW_DATA_QUERY'
}

const loadMeta = async () => {
	try {
		updateTypeByTab()
		const [dimsRes, fieldsRes] = await Promise.all([
			getGroupDimensions(form.queryType),
			getOutputFields(form.queryType)
		])
		groupDimensionOptions.value = dimsRes.data.data || []
		outputFieldOptions.value = fieldsRes.data.data || []
		// 默认把“关区/进出口类型”加入分组，便于后端给出维度
		await loadCustomsAreas()
	} catch (e) {
		ElMessage.error(e.message || '加载可选项失败')
	}
}

// 加载关区列表：调用汇总接口，按 customs_area 分组
const loadCustomsAreas = async () => {
	try {
		const payload = {
			queryType: 'SUMMARY_QUERY',
			groupDimensions: ['customs_area'],
			outputFields: [],
			pageNum: 1,
			pageSize: 1000
		}
		const res = await summaryQuery(payload)
		const rows = res.data.data || []
		customsOptions.value = rows
			.map(r => r?.dimensionValues?.customs_area)
			.filter(v => v)
			.map(v => ({ label: String(v), value: String(v) }))
	} catch (e) {
		// 忽略错误，不阻塞主流程
	}
}

const syncDates = () => {
	form.customsClearanceStartDate = dateRange.value?.[0] ? `${dateRange.value[0]} 00:00:00` : ''
	form.customsClearanceEndDate = dateRange.value?.[1] ? `${dateRange.value[1]} 23:59:59` : ''
}

// 去除空值字段，避免把空条件提交给后端
const sanitizeForm = (obj) => {
	const copy = JSON.parse(JSON.stringify(obj))
	
	// 对于数据查询和原始数据查询，更宽松的过滤条件
	if (activeTab.value === 'data' || activeTab.value === 'raw') {
		// 数据查询时，如果进出口类型为空，不传这个字段
		if (!copy.importExportType || !String(copy.importExportType).trim()) {
			delete copy.importExportType
		}
		// 关区为空时不传
		if (!copy.customsCode || !String(copy.customsCode).trim()) {
			delete copy.customsCode
		}
		// 日期为空时不传
		if (!copy.customsClearanceStartDate) delete copy.customsClearanceStartDate
		if (!copy.customsClearanceEndDate) delete copy.customsClearanceEndDate
		
		// 确保只传必要的字段
		const minimalData = {
			queryType: copy.queryType,
			pageNum: copy.pageNum,
			pageSize: copy.pageSize
		}
		
		// 只有当字段有值时才添加
		if (copy.importExportType) minimalData.importExportType = copy.importExportType
		if (copy.customsCode) minimalData.customsCode = copy.customsCode
		if (copy.customsClearanceStartDate) minimalData.customsClearanceStartDate = copy.customsClearanceStartDate
		if (copy.customsClearanceEndDate) minimalData.customsClearanceEndDate = copy.customsClearanceEndDate
		
		return minimalData
	} else {
		// 汇总查询保持原有逻辑
		if (!copy.customsCode || !String(copy.customsCode).trim()) {
			delete copy.customsCode
		} else {
			const codeStr = String(copy.customsCode).trim()
			const isNumericCode = /^\d+$/.test(codeStr)
			if (!isNumericCode) {
				copy.filterConditions = copy.filterConditions || {}
				copy.filterConditions.customs_area = codeStr
				delete copy.customsCode
			}
		}
		if (!copy.customsClearanceStartDate) delete copy.customsClearanceStartDate
		if (!copy.customsClearanceEndDate) delete copy.customsClearanceEndDate
		return copy
	}
}

const handleSearch = async () => {
	loading.value = true
	try {
		syncDates()
		const submitData = sanitizeForm(form)
		console.log('提交的查询条件:', submitData) // 调试用
		await validateConditions(submitData)
		let res
		if (activeTab.value === 'summary') {
			res = await summaryQuery(submitData)
			tableData.value = res.data.data || []
			total.value = tableData.value.length
		} else if (activeTab.value === 'data') {
			res = await dataQuery(submitData)
			console.log('后端返回数据:', res.data) // 调试用
			tableData.value = res.data.data?.records || []
			total.value = res.data.data?.total || 0
		} else {
			res = await rawDataQuery(submitData)
			console.log('后端返回数据:', res.data) // 调试用
			tableData.value = res.data.data?.records || []
			total.value = res.data.data?.total || 0
		}
	} catch (e) {
		console.error('查询错误:', e) // 调试用
		// 拦截器已提示
	} finally {
		loading.value = false
	}
}

const handleExport = async () => {
	try {
		const type = activeTab.value === 'summary' ? 'SUMMARY' : activeTab.value === 'data' ? 'DATA' : 'RAW_DATA'
		syncDates()
		const submitData = sanitizeForm(form)
		const res = await exportQuery(submitData, type)
		const blob = new Blob([res.data])
		const url = window.URL.createObjectURL(blob)
		const a = document.createElement('a')
		a.href = url
		a.download = `export_${type.toLowerCase()}.xlsx`
		a.click()
		window.URL.revokeObjectURL(url)
	} catch (e) {
		// 已有提示
	}
}

onMounted(() => {
	loadMeta()
})
</script>

<template>
	<div class="page">
		<div class="header">
			<h2>海关多维查询</h2>
		</div>

		<el-card class="query-card">
			<el-tabs v-model="activeTab" @tab-change="loadMeta">
				<el-tab-pane label="汇总查询" name="summary" />
				<el-tab-pane label="处理表数据" name="data" />
				<el-tab-pane label="原始数据" name="raw" />
			</el-tabs>

			<el-form label-width="120px" class="form">
				<el-row :gutter="12">
					<el-col :span="6">
						<el-form-item label="进出口类型">
							<el-select v-model="form.importExportType" placeholder="选择类型">
								<el-option label="全部" value="" />
								<el-option label="进口" value="进口" />
								<el-option label="出口" value="出口" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="关区代码">
							<el-select v-model="form.customsCode" filterable clearable placeholder="选择关区">
								<el-option v-for="opt in customsOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="10">
						<el-form-item label="结关日期">
							<el-date-picker
								v-model="dateRange"
								type="daterange"
								format="YYYY-MM-DD"
								value-format="YYYY-MM-DD"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
							/>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="12" v-if="activeTab === 'summary'">
					<el-col :span="12">
						<el-form-item label="分组维度 (≤3)">
							<el-select v-model="form.groupDimensions" multiple :max-collapse-tags="3" :multiple-limit="3" placeholder="选择维度">
								<el-option v-for="d in groupDimensionOptions" :key="d" :label="toLabel(d)" :value="d" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="输出字段">
							<el-select v-model="form.outputFields" multiple :max-collapse-tags="4" placeholder="选择字段">
								<el-option v-for="f in outputFieldOptions" :key="f" :label="toLabel(f)" :value="f" />
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>

				<div class="actions">
					<el-button type="primary" :loading="loading" @click="handleSearch">查询</el-button>
					<el-button @click="handleExport">导出</el-button>
				</div>
			</el-form>
		</el-card>

		<el-card class="result-card">
			<!-- 汇总查询表格 -->
			<el-table v-if="activeTab === 'summary'" :data="tableData" border v-loading="loading" height="520">
				<el-table-column prop="dimensionValues" label="维度值" min-width="200">
					<template #default="scope">
						<div v-for="(dimVal, dimKey) in scope.row.dimensionValues" :key="dimKey" class="dimension-item">
							<span class="dimension-label">{{ toLabel(dimKey) }}:</span>
							<span class="dimension-value">{{ dimVal }}</span>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="declareCount" label="报关单数量" min-width="120" />
				<el-table-column prop="recordCount" label="记录数量" min-width="120" />
				<el-table-column prop="amountCny" label="货值(人民币)" min-width="140" />
				<el-table-column prop="amountUsd" label="货值(美元)" min-width="140" />
				<el-table-column prop="goodsQuantity" label="商品数量" min-width="120" />
			</el-table>
			
			<!-- 处理表数据和原始数据表格 -->
			<el-table v-else :data="tableData" border v-loading="loading" height="520">
				<el-table-column prop="id" label="ID" min-width="80" />
				<el-table-column prop="dataType" label="数据类型" min-width="100">
					<template #default="scope">
						{{ getDataTypeLabel(scope.row.dataType) }}
					</template>
				</el-table-column>
				<el-table-column prop="customsArea" label="关区" min-width="120" />
				<el-table-column prop="declareNo" label="报关单号" min-width="150" />
				<el-table-column prop="itemNo" label="商品项号" min-width="100" />
				<el-table-column prop="currencyType" label="货币类型" min-width="100">
					<template #default="scope">
						{{ getCurrencyTypeLabel(scope.row.currencyType) }}
					</template>
				</el-table-column>
				<el-table-column prop="amountCny" label="货值(人民币)" min-width="120" />
				<el-table-column prop="amountUsd" label="货值(美元)" min-width="120" />
				<el-table-column prop="goodsQuantity" label="商品数量" min-width="100" />
				<el-table-column prop="status" label="状态" min-width="80">
					<template #default="scope">
						{{ getStatusLabel(scope.row.status) }}
					</template>
				</el-table-column>
				<el-table-column prop="createTime" label="创建时间" min-width="150" />
				<el-table-column prop="userName" label="操作人" min-width="100" />
				<el-table-column prop="importExportType" label="进出口类型" min-width="100" />
			</el-table>
			
			<div class="pager" v-if="activeTab !== 'summary'">
				<el-pagination
					v-model:current-page="form.pageNum"
					v-model:page-size="form.pageSize"
					:total="total"
					layout="prev, pager, next, sizes, jumper"
					@current-change="handleSearch"
					@size-change="handleSearch"
				/>
			</div>
		</el-card>
	</div>
</template>

<style scoped>
.page { padding: 16px; }
.header { margin-bottom: 12px; }
.query-card { margin-bottom: 12px; }
.form :deep(.el-form-item) { margin-bottom: 12px; }
.actions { display: flex; gap: 8px; justify-content: flex-end; }
.result-card { }
.pager { margin-top: 10px; display: flex; justify-content: center; }

.dimension-item {
	display: flex;
	align-items: center;
	gap: 4px;
	margin-bottom: 2px;
}
.dimension-item:last-child {
	margin-bottom: 0;
}
.dimension-label {
	font-weight: 500;
	color: #606266;
	font-size: 12px;
}
.dimension-value {
	color: #303133;
	font-size: 12px;
}
</style>